import db

def Login(Db):

    DATA = Db
    account = None
    for _ in range(3):
        account = input("请输入账号：").strip()
        passwor = input("请输入密码：").strip()

        if (account, passwor) in DATA:
            break
        else:
            print("密码错误！请重新输入！")
    else:
        print("3次输入错误，正在退出系统")
        exit(0)
    return account

def Register(Db):
    AccountSet = [i[0] for i in Db]
    TempAccount = None
    psw = None
    account = None
    passwor = None
    while True:
        if TempAccount is None:
            account = input("请输入账号：").strip()
        else:
            account = TempAccount
        if account in AccountSet:
            print("账号已存在，请重新输入！！")
            account = TempAccount
            continue

        if psw is None:
            passwor = input("请输入密码：").strip()
            if len(passwor) < 6:
                print("密码长度小于6，请重新输入")
                TempAccount = account
                continue
        else:
            passwor = psw

        confident_password = input("请再次确认密码: ")
        if confident_password == passwor:
            print("注册成功！")
            break
        else:
            print("两次密码不一样，请重新输入！！")
            psw = passwor
            continue
    return account, passwor

class Oprating:
    def __init__(self, ):
        self.__db = db.DBOperate("USER.db")
        TableName = self.__db.Query("SELECT name FROM sqlite_master where type='table' order by name;")
        if ('USER',) not in TableName:
            self.defaultUser()

    def defaultUser(self):
        self.__db.defaultSQL("""
    CREATE TABLE USER
    (account char(20) NOT NULL,
    password char(20) NOT NULL,
    DAY CHAR(50) NOT NULL);
    """)
        self.__db.Insert(f"INSERT INTO USER (account, password, DAY) "
              f"VALUES ('admin', 'admin', '1')")

    def SELECT_User(self):
        return self.__db.Query(f"SELECT account, password FROM USER")

    def LoginUser(self):
        data =  self.SELECT_User()
        return Login(data)

    def RegisterUser(self):
        data = self.SELECT_User()
        result = Register(data)

        if result:
            self.__db.Insert(f"INSERT INTO USER (account, password, DAY) "
                             f"VALUES ('{result[0]}', '{result[1]}', '0')")
            return result[0]
        else:return 0

    def GetDay(self, user):
        return self.__db.Query(f"SELECT DAY FROM USER WHERE account = '{user}'")

    def AddDAY(self, user, day):
        return self.__db.Update(f"UPDATE USER SET DAY = '{day+1}' WHERE account = '{user}';")